package cn.duxiaod.demo.producerconsumer.a;

import java.util.Queue;
import java.util.Random;

public class Producer extends Thread{
    private Queue queue;
    private Integer maxSize;
    //生产者名称
    private String name;
    private Integer i = 0;

    public Producer(String name,Queue<Integer> queue,Integer maxSize){
        super(name);
        this.name = name;
        this.queue = queue;
        this.maxSize = maxSize;
    }
    @Override
    public void run() {
        while (true){
            synchronized (queue){
                while (queue.size()==maxSize){
                    try {
                        System.out.println("队列满，生产者线程[" + name + "]等待消费！");
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("[" + name + "]生产值为：" + i);
                queue.offer(i++);
                queue.notifyAll();
                try {
                    Thread.sleep(new Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
